﻿/*
* @Author: z.p
* @Project: Zdotp
* @Date: 2024年12月31日
* @Description: 基于pb实现前后端消息的序列化和反序列化
*/

using System.Reflection;
using Google.Protobuf;
using Zdotp.Net.NetMessageHandler;

namespace Zdotp.Pb;

public static class PbTool
{
    public static byte[] Serialize<T>(this T message) where T : IMessage<T> => message.ToByteArray();
    public static T Deserialize<T>(this byte[] data) where T : IMessage<T>
    {
        var messageParser = KcpNetHandlerManager.GetParser<T>();
        if (messageParser == null)
        {
            var type = typeof(T);
            var parserProperty = type.GetProperty("Parser", BindingFlags.Public | BindingFlags.Static);
            var value = parserProperty?.GetValue(null);
            if (value is MessageParser<T> parser)
            {
                KcpNetHandlerManager.AddParser(type, value);
                return parser.ParseFrom(data);
            }
            return default;
        }
        return messageParser.ParseFrom(data);
    }
}